package com.abou.mvc.validation.impl;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import org.apache.commons.lang.StringUtils;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import com.abou.model.common.product.Product;
import com.abou.mvc.validation.annotation.ProductMultipartValid;

/**
 * The validator used to check that a product object contains consistent values
 * 
 * @author khalid
 */
public class MultipartValidConstraintValidator implements
    ConstraintValidator<ProductMultipartValid, Product> {
  
  /**
   * @see javax.validation.ConstraintValidator#initialize(java.lang.annotation.Annotation)
   */
  public void initialize(ProductMultipartValid annotation) {

  }
  
  /**
   * @see javax.validation.ConstraintValidator#isValid(java.lang.Object,
   *      javax.validation.ConstraintValidatorContext)
   */
  public boolean isValid(Product product, ConstraintValidatorContext context) {

    boolean isValid = true;
    
    CommonsMultipartFile image = product.getImage1();
    String imagePath = product.getImagePath1();
    
    if (image != null) {
      
      if (image.isEmpty() || !image.getContentType().contains("image")
          || StringUtils.isBlank(image.getOriginalFilename())
          || image.getFileItem() == null) {
        
        ConstraintValidatorContext.ConstraintViolationBuilder builder =
            context.buildConstraintViolationWithTemplate("");
        builder.addNode("image1").addConstraintViolation();
        
        isValid = false;
      }
      
    } else {
      
      if (StringUtils.isBlank(imagePath)) {
        
        ConstraintValidatorContext.ConstraintViolationBuilder builder =
            context.buildConstraintViolationWithTemplate("");
        builder.addNode("imagePath1").addConstraintViolation();
        
        isValid = false;
      }
    }
    
    System.out.println(" image1 " + image);
    System.out.println(" imagePath1 " + imagePath);
    System.out.println(" isValid " + isValid);
    
    return isValid;
  }
}
